package util;

import java.io.File;
import java.io.FileInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.jpeg.JpegParser;
import org.apache.tika.sax.BodyContentHandler;

public class TikaTool {

  public static void main(String[] args) throws Exception {
    String fileName = "D:\\2.jpg";
    parseImage(fileName);
  }

  //获取文本内容
  public static void fileContent(String fileName) throws Exception {
    //creating the file object
    File file = new File(fileName);

    //using tika facade
    org.apache.tika.Tika tika = new org.apache.tika.Tika();
    String filecontent = tika.parseToString(file);
    System.out.println("Extracted Content: " + filecontent);
  }

  //获取文件类型，为MiMe标准
  public static void fileType(String fileName) throws Exception {
    //creating file object
    File file = new File(fileName);//

    //using tika facade class
    org.apache.tika.Tika tika = new org.apache.tika.Tika();

    //detecting the file type using detect method
    String filetype = tika.detect(file);
    System.out.println(filetype);
  }


  //解析图片元数据
  public static void parseImage(String fileName) throws Exception {

    //detecting the file type
    BodyContentHandler handler = new BodyContentHandler();
    Metadata metadata = new Metadata();
    FileInputStream inputstream = new FileInputStream(new File(fileName));
    ParseContext pcontext = new ParseContext();

    //Jpeg Parse
    JpegParser JpegParser = new JpegParser();
    JpegParser.parse(inputstream, handler, metadata, pcontext);
    System.out.println("Contents of the document:" + handler.toString());
    System.out.println("Metadata of the document:");
    String[] metadataNames = metadata.names();

    for (String name : metadataNames) {
      System.out.println(name + ": " + metadata.get(name));
    }
  }

}
